package com.cloud.school.app.service.impl;

import com.cloud.school.app.entity.TbChatRoom;
import com.cloud.school.app.mapstruct.IChatRoomConvertMapper;
import com.cloud.school.app.model.ChatRoomModel;
import com.cloud.school.app.repository.TbChatRoomMapper;
import com.cloud.school.app.service.ChatRoomService;
import com.cloud.school.app.util.IdWorker;
import com.cloud.school.app.util.Pager;
import com.cloud.school.app.util.exception.SystemHandleException;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Set;

import static com.cloud.school.app.config.CloudSchoolProperties.MAX_PAGE_PER_COUNT;
import static com.cloud.school.app.controller.ChatRoomController.CHAT_ROOM_USER_ID_KEY;
import static com.cloud.school.app.service.impl.ChatWebSocketHandler.USER_ID_SESSION_ID_MAP_KEY;

/**
 * @ClassName ChatRoomServiceImpl
 * @Description TODO
 * @Author 36297
 * @Date 2019/1/6 10:21
 * @Version 1.0
 */
@Service
public class ChatRoomServiceImpl implements ChatRoomService {

    @Autowired
    private TbChatRoomMapper tbChatRoomMapper;
    @Autowired
    private IChatRoomConvertMapper chatRoomConvertMapper;
    @Autowired
    private IdWorker chatRoomIdWorker;
    @Autowired
    private CacheService cacheService;

    @Override
    @Transactional
    public boolean save(ChatRoomModel chatRoomModel) {
        TbChatRoom chatRoom = new TbChatRoom();
        chatRoom.setName(chatRoomModel.getName());
        if (tbChatRoomMapper.selectCount(chatRoom) > 0) {
            throw new SystemHandleException("聊天室名称重复!");
        }
        chatRoomModel.setCreateTime(System.currentTimeMillis());
        chatRoomModel.setId(chatRoomIdWorker.nextId());
        return tbChatRoomMapper.insert(chatRoomConvertMapper.modelToEntity(chatRoomModel)) > 0;
    }

    @Override
    public boolean delete(Long chatRoomId) {
        return tbChatRoomMapper.deleteByPrimaryKey(chatRoomId) > 0;
    }

    @Override
    public List<ChatRoomModel> selectAll() {
        List<ChatRoomModel> chatRoomModels = chatRoomConvertMapper.entityToModel(tbChatRoomMapper.selectAll());
        setOnLineNum(chatRoomModels);
        return chatRoomModels;
    }

    @Override
    public List<ChatRoomModel> selectByNameLike(String name) {
        Example example = new Example(TbChatRoom.class);
        example.createCriteria().andLike("name", "%" + name + "%");
        List<ChatRoomModel> chatRoomModels = chatRoomConvertMapper.entityToModel(tbChatRoomMapper.selectByExample(example));
        setOnLineNum(chatRoomModels);
        return chatRoomModels;
    }

    @Override
    public Pager<ChatRoomModel> selectAll(int pNo) {
        PageHelper.startPage(pNo, MAX_PAGE_PER_COUNT);
        List<TbChatRoom> chatRooms = tbChatRoomMapper.selectAll();
        Pager result = Pager.build(chatRooms);
        List<ChatRoomModel> chatRoomModels = chatRoomConvertMapper.entityToModel(chatRooms);
        setOnLineNum(chatRoomModels);
        result.setResultList(chatRoomModels);
        return result;
    }

    private void setOnLineNum(List<ChatRoomModel> chatRoomModels) {
        chatRoomModels.forEach(chatRoomModel -> {
            Set<String> uStrs = cacheService.setMembers(CHAT_ROOM_USER_ID_KEY + chatRoomModel.getId());
            if (CollectionUtils.isEmpty(uStrs)) {
                chatRoomModel.setOnLineNum(0l);
            } else {
                Long onLineNum = uStrs.stream().filter(id -> cacheService.hashHasKey(USER_ID_SESSION_ID_MAP_KEY, id)).count();
                chatRoomModel.setOnLineNum(onLineNum);
            }
        });
    }
}
